#! /usr/bin/python
#######################################################################################
#                                                                                     #
#    File: achievement.py                                                               #
#    Part of 2dgal-cheater                                                            #
#    Home: http://2dgal-cheater.googlecode.com                                        #
#                                                                                     #
#    The MIT License                                                                  #
#                                                                                     #
#    Copyright (c) 2010-2011 <araya.akashic@gmail.com>                                #
#                                                                                     #
#    Permission is hereby granted, free of charge, to any person obtaining a copy     #
#    of this software and associated documentation files (the "Software"), to deal    #
#    in the Software without restriction, including without limitation the rights     #
#    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell        #
#    copies of the Software, and to permit persons to whom the Software is            #
#    furnished to do so, subject to the following conditions:                         #
#                                                                                     #
#    The above copyright notice and this permission notice shall be included in       #
#    all copies or substantial portions of the Software.                              #
#                                                                                     #
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR       #
#    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,         #
#    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE      #
#    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER           #
#    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,    #
#    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN        #
#    THE SOFTWARE.                                                                    #
#                                                                                     #
#######################################################################################
# This code is to automatically submit test result for 2dgal bbs star 1
# Created as CKJ's demand (wtf)

# Author: Araya

import time

import urllib
import urllib2

import gojuon
from browser_bogus import Browser

#customized these
#adding account as "username":"password"
account_list = {"":"",
                "":""}

#total attempts
cycle = 1
#wait 1 hr 10 s before each attempt
delay = 3610

#do not change below this
siteurl = "http://bbs.9gal.com"
login_page = "login.php"
achievement_page = "kf_star_1.php"

#submit data tail
data_tail = "ok=99&submit=%BF%AA%CA%BC%B2%E2%CA%D4"
        
class ExamNotAvailable(Exception):
    def __init__(self, time):
        self.value = time
        
    def __str__(self):
        return repr(self.value)
    
class LoginFailed(Exception):
    def __init__(self, str):
        self.value = str
        
    def __str__(self):
        return repr(self.value)
    

#method login
def login(user):
    logindata = {"pwuser":user.username,
                 "pwpwd":user.password,
                 "hideid":"0",
                 "cktime":"0",
                 "forward":"index.php",
                 "jumpurl":"index.php",
                 "step":"2"}
    
    en_logindata = urllib.urlencode(logindata)
    print en_logindata
    url = siteurl + "/" + login_page
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    #print "Getting login page"
    url = url + "?"
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    print "Login " + user.username
    #print cookie
    
def parse_logout_URI(page):
    begin = page.find(logout_hint)
    if begin >= 0:
        end = page[begin:].find("\"")
        return page[begin:end]
        
    return ""
    
def achievement_cheat(user):
    question = []
    answer = ""
    #print "Getting star 1 question"
    url = siteurl + "/" + achievement_page
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    
    pagelines = result.readlines()
    #print len(pagelines)
    user.logout_URI = parse_logout_URI(result)
#    for line in pagelines:
        #extracting logout URI
#        if line.find(login_page) >= 0:
#            user.logout_URI = line.split("=\"")[-1].split("\"")[0]
    
    #checking time to next exam
    try:
        timetoexam = int(pagelines[166][:2])
    except:
        timetoexam = 0
        
    if timetoexam > 0:
        raise ExamNotAvailable(timetoexam)
    
    #parse questions
    for i in range(0,5):
        for line in pagelines:
            search_str = "\"s1_" + str(i) + "\""
            if line.find(search_str) >= 0:
                ques = line.split("=\"")[-1].split("\"")[0]
                print ques,
                question.append(urllib.urlencode({"":ques}))
        
    print " "
    #print "Answer:"
    
    for i in range(0,5):
        phonetic = gojuon.gojuon[question[i]]
        print phonetic + " ",
        ans = "s1_%d%s&s1_%d_ans=%s&" % (i, question[i], i, phonetic)
        if i == 0:
            answer = ans
        else:
            answer = answer + ans
    print " "
    #print "Answer: " + answer
    
    answer_data = answer + data_tail
    request = urllib2.Request(url, answer_data)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    print "Answer sent"
    result_data = result.read()
    return result_data.find("+1")
#    return 1

    
    
def logout(user):
    url = siteurl + "/" + user.logout_URI
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    print "Logout " + user.username
    
def perform_cheating():
    for n, p in account_list.iteritems():
        user = Browser(n, p)
        submit_success = -1
        try:
            login(user)
            while submit_success < 0:
                try:
                    submit_success = achievement_cheat(user)
                except ExamNotAvailable, e:
                    print "Time to next exam is: " + str(e.value)
                    break
                #print submit_success
            logout(user)
        except:
            pass
        
    
if __name__ == "__main__":
    while cycle:
        print "------------------------------------------"
        print time.strftime("%a, %b %d %Y %H:%M:%S", time.localtime()) + "-----------------"
        perform_cheating()
        if cycle > 1:
            time.sleep(delay)
        cycle = cycle - 1